package org.gwh.airagknowledge.core.llm.impl;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.gwh.airagknowledge.core.llm.LlmService;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * LLM工厂类，用于根据配置或运行时选择使用不同的LLM模型
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LlmFactory {
    
    private final OllamaLlmService ollamaLlmService;
    private final ChatGlmLlmService chatGlmLlmService;
    private final DeepSeekLlmService deepSeekLlmService;
    
    @Value("${llm.default-provider:ollama}")
    private String defaultProvider;
    
    private final Map<String, LlmService> llmServices = new HashMap<>();
    private LlmService currentLlmService;
    
    @PostConstruct
    public void init() {
        // 注册所有可用的LLM服务
        llmServices.put("ollama", ollamaLlmService);
        llmServices.put("chatglm", chatGlmLlmService);
        llmServices.put("deepseek", deepSeekLlmService);
        
        // 设置默认LLM服务
        currentLlmService = llmServices.getOrDefault(
                defaultProvider, 
                ollamaLlmService // 如果默认提供商配置无效，使用Ollama作为后备
        );
        
        log.info("LLM Factory initialized with default provider: {}", currentLlmService.getModelName());
    }
    
    /**
     * 获取当前使用的LLM服务
     */
    public LlmService getCurrentLlmService() {
        return currentLlmService;
    }
    
    /**
     * 切换LLM服务提供商
     * 
     * @param provider LLM提供商名称 (ollama, chatglm, deepseek)
     * @return 切换是否成功
     */
    public boolean switchLlmProvider(String provider) {
        if (llmServices.containsKey(provider)) {
            currentLlmService = llmServices.get(provider);
            log.info("Switched LLM provider to: {}", provider);
            return true;
        } else {
            log.warn("Failed to switch LLM provider. Unknown provider: {}", provider);
            return false;
        }
    }
    
    /**
     * 获取所有可用的LLM提供商列表
     */
    public Map<String, String> getAvailableProviders() {
        Map<String, String> providers = new HashMap<>();
        llmServices.forEach((key, service) -> 
                providers.put(key, service.getModelName()));
        return providers;
    }
    
    /**
     * 为当前模型设置温度参数
     */
    public void setTemperature(double temperature) {
        if (temperature < 0 || temperature > 1) {
            throw new IllegalArgumentException("Temperature must be between 0 and 1");
        }
        
        currentLlmService.setTemperature(temperature);
        log.info("Set temperature to {} for model: {}", temperature, currentLlmService.getModelName());
    }
} 